package com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.memberrecharge;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.yzy.voice.VoicePlay;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.common.RechargeSuccessFragment;
import com.zzsy.carosshopprojects.activitys.home.mainpage.common.scan.ScanOnlyAc;
import com.zzsy.carosshopprojects.adapter.RechargeAdapter;
import com.zzsy.carosshopprojects.base.BaseActivity;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.RechargeDataBean;
import com.zzsy.carosshopprojects.util.Cons;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.HUD;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.Util;
import com.zzsy.carosshopprojects.view.dialog.ComTwoBtnDialog;

import java.math.BigDecimal;
import java.util.ArrayList;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 吧台端会员充值界面
 */
public class RechargePayTwoFragment extends BaseFragment {

    public static RechargePayTwoFragment newInstance(String amount, String memberId, String productId, String activityId, String activityPositionId,
                                                     String memberCardId, String phone, String receiveAmount, String activitySummary, ArrayList<RechargeDataBean> rechargeDataBeanList) {
        RechargePayTwoFragment rechargePayTwoFragment = new RechargePayTwoFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("couponList", rechargeDataBeanList);
        bundle.putString("amount", amount);
        bundle.putString("memberId", memberId);
        bundle.putString("productId", productId);
        bundle.putString("activityId", activityId);
        bundle.putString("activityPositionId", activityPositionId);
        bundle.putString("memberCardId", memberCardId);
        bundle.putString("phone", phone);
        bundle.putString("receiveAmount", receiveAmount);
        bundle.putString("activitySummary", activitySummary);
        bundle.putString("activitySummary", activitySummary);
        rechargePayTwoFragment.setArguments(bundle);
        return rechargePayTwoFragment;
    }

    @BindView(R.id.btn_wechat)
    Button btnWechat;
    @BindView(R.id.btn_alipay)
    Button btnAlipay;
    @BindView(R.id.btn_unionpay)
    Button btnUnion;
    @BindView(R.id.btn_yue)
    Button btnYue;

    @BindView(R.id.tv_regter_money)
    TextView tvReghterMouny;
    @BindView(R.id.tv_activity)
    TextView tvActivity;
    @BindView(R.id.rv_view)
    RecyclerView rvView;

    //后台传递数据
    private String activityId;
    private String activityPositionId;
    private String serviceCardIds = "";
    private String couponIds = "";
    private String terminalId;
    private String staffId;
    private String storeId;
    private String productId;
    private String amount;
    private String memberId;
    private String payType;
    private RechargeAdapter rechargeAdapter;
    private String memberCardId;
    private String phone;
    private String receiveAmount = "";
    private String activitySummary;
    private String musicSwitch;
    private ComTwoBtnDialog comTwnBtnDialog;
    private String rechargeNumber;
    private ArrayList<RechargeDataBean> couponList;
    private RechargePayTwoMode rechargePayTwoMode;
    private String[] permissionArrs = {Manifest.permission.CAMERA};
    private boolean isClickBank = true;
    private boolean isFirstBnakPay = true;
    @Override
    protected int initLayout() {
        return R.layout.fg_recharge_pay_two;
    }

    @Override
    protected void initView(View view) {
        initTitle(view, getResources().getString(R.string.MemberRecharge), getActivity());
    }

    @Override
    protected void initData(Context mContext) {
        musicSwitch = DataUtil.getInstance().getMusicSwitch();
        rechargePayTwoMode = getViewModelProvider().get(RechargePayTwoMode.class);
        memberId = getArguments().getString("memberId");
        amount = getArguments().getString("amount");
        productId = getArguments().getString("productId");
        activityId = getArguments().getString("activityId");
        activityPositionId = getArguments().getString("activityPositionId");
        memberCardId = getArguments().getString("memberCardId");
        phone = getArguments().getString("phone");
        receiveAmount = getArguments().getString("receiveAmount");
        activitySummary = getArguments().getString("activitySummary");
        couponList = (ArrayList<RechargeDataBean>) getArguments().getSerializable("couponList");
        double amountAmount = ConverterHelper.toBigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvReghterMouny.setText("￥" + amountAmount);
        staffId = "";
    }

    @Override
    protected void loadMethod() {
        setNotify(couponList);
        setPrintList(couponList, activitySummary);
        orderResult();
    }


    @OnClick({R.id.btn_wechat, R.id.btn_alipay, R.id.btn_unionpay, R.id.btn_yue})
    public void onViewClicked(View view) {
//        if (ThrottleFirstUtil.isFastClick()) {
//            ToastUtils.showToast(context, getContext().getResources().getString(R.string.FastClick));
//            return;
//        }
        if (StringUtils.isEmpty(memberId)) {
            ToastUtils.showToast(getContext(), "会员信息异常！");
            return;
        }
        switch (view.getId()) {
            case R.id.btn_wechat:
                //微信支付
                payType = "2";
                toPay();
                break;
            case R.id.btn_alipay:
                //支付宝支付
                payType = "1";
                toPay();
                break;
            case R.id.btn_unionpay:
                //银行卡支付
                if (isClickBank) {
                    isClickBank = false;
                    payType = "3";
                    toPay();
                } else {

                }

                break;
            case R.id.btn_yue:
                //余额支付
                comTwnBtnDialog = new ComTwoBtnDialog(getActivity(), ComTwoBtnDialog.BANBALCE_PAY, null);
                comTwnBtnDialog.show();
                comTwnBtnDialog.setDialogBtnClickListener(new ComTwoBtnDialog.IDialogBtnClickListener() {
                    @Override
                    public void onDialogLeftBtnClick() {
                        comTwnBtnDialog.dismiss();
                    }

                    @Override
                    public void onDialogRightBtnClick() {
                        payType = "5";
                        toPay();
                    }
                });
                break;
        }
    }

    /**
     * 传递到后台接口的数据
     */
    private void setNotify(ArrayList<RechargeDataBean> couponList) {
        serviceCardIds = "";
        couponIds = "";

        if (couponList != null && couponList.size() != 0) {
            for (int i = 0; i < couponList.size(); i++) {
                if ("1".equals(couponList.get(i).getType())) {
                    couponIds += "," + String.valueOf(couponList.get(i).getCouponId());
                } else if ("2".equals(couponList.get(i).getType())) {
                    serviceCardIds += "," + String.valueOf(couponList.get(i).getCouponId());
                }

            }
        }
    }

    /**
     * 数据的展示
     */
    private void setPrintList(ArrayList<RechargeDataBean> couponList, String activitySummary) {

        if (!StringUtils.isEmpty(activitySummary)) {
            tvActivity.setVisibility(View.VISIBLE);
            rvView.setVisibility(View.GONE);
            tvActivity.setText(activitySummary);
        } else if (couponList != null && couponList.size() != 0) {
            tvActivity.setVisibility(View.GONE);
            rvView.setVisibility(View.VISIBLE);
            rvView.setLayoutManager(new GridLayoutManager(getContext(), 2));
            rechargeAdapter = new RechargeAdapter(getContext(), couponList, 0);
            rvView.setAdapter(rechargeAdapter);
        } else {
            tvActivity.setVisibility(View.GONE);
            rvView.setVisibility(View.GONE);
        }
    }

    private void toPay() {
        rechargePayTwoMode.toPay(getActivity(), couponIds, amount, serviceCardIds, activityId, activityPositionId, memberCardId, memberId, payType, phone, receiveAmount, productId);
    }

    /**
     * 支付订单结果
     */
    private void orderResult() {
        rechargePayTwoMode.getLiveOrderData().observe(this, orderResultBean -> {
            if (orderResultBean == null) {
                getActivity().finish();
            } else {
                Scanner(orderResultBean.getType(), orderResultBean.getPayAmount(), orderResultBean.getOrderNumber());
            }

        });
    }

    /**
     * 进行扫描数据 通过微信支付宝支付
     */
    private void Scanner(String payType, String payAmount, String orderNumber) {
        if (EasyPermissions.hasPermissions(getActivity(), permissionArrs)) {
            if (payType.equals(ConfigureFile.CARDPAY))
                bankCardPay(payAmount, orderNumber);
            else if (payType.equals(ConfigureFile.YUEPAY)) {
                toPayYue(orderNumber, payAmount);
            } else {
                ScanOnlyAc.start(getContext(), "5", payAmount, payType, orderNumber);
                getActivity().finish();
            }

        } else {
            EasyPermissions.requestPermissions(getActivity(), getResources().getString(R.string.get_photo_permission_tip), 0x11, permissionArrs);
        }
    }

    /**
     * 银行卡支付
     */
    private void bankCardPay(String payAmount, String orderNumber) {
        if (!isFirstBnakPay) {
            return;
        }
        isFirstBnakPay = false;
        HUD.getInstance().show(getContext(), "跳转中...");
        ComponentName component = new ComponentName("com.fuyousf.android.fuious", "com.fuyousf.android.fuious.MainActivity");
        Intent intent = new Intent();
        intent.setComponent(component);
        Bundle bundle = new Bundle();
        try {
            bundle.putString("transName", "消费");
            long m = Long.parseLong(String.valueOf(payAmount));
            bundle.putString("amount", String.format("%012d", m));
            bundle.putString("orderNumber", orderNumber);
            bundle.putString("isPrintTicket", "false");
            bundle.putString("version", Cons.version);
        } catch (Exception e) {
            ToastUtils.showToast(getContext().getApplicationContext(), getResources().getString(R.string.payAccountError));
            getActivity().finish();
            return;
        }
        if (Util.isIntentExisting(intent, getContext())) {
            intent.putExtras(bundle);
            getActivity().startActivityForResult(intent, BaseActivity.REQUEST_CODE);
        } else {
            getActivity().finish();
            ToastUtils.showToast(getContext().getApplicationContext(), getResources().getString(R.string.L3));
        }
    }

    /**
     * 余额支付
     *
     * @param rechargeNumber
     * @param amountStr
     */
    private void toPayYue(String rechargeNumber, String amountStr) {
        //进行语音播报
        if (!StringUtils.isEmpty(musicSwitch)) {
            if ("1".equals(musicSwitch)) {
                MusicTell(amountStr);
            }
        }
        startWithPop(RechargeSuccessFragment.newInstance(rechargeNumber));
    }

    /**
     * 进行语音播报
     */
    private void MusicTell(String payAmount) {
        String amounts = ConverterHelper.toBigDecimal(payAmount).divide(ConverterHelper.toBigDecimal(100)).toString();
        VoicePlay.with(getActivity()).play(amounts, false);
    }
}
